package custome

import (
	"fmt"
	"strconv"
	"sync"
	"time"
)

type CacheIF interface {
	SetV(key,value string)
	GetV(key string)string
}

type CacheS struct {
	sync.RWMutex
	m map[string]map[string]string
}
var(
	o *CacheS
	once sync.Once
)

func (o *CacheS)SetV(key,value string)  {
	o.Lock()
	defer o.Unlock()
	submap:=make(map[string]string,2)
	submap["value"]=value
	submap["time"]=fmt.Sprintf("%d",time.Now().Unix())
	o.m[key]=submap

}
func (o *CacheS)GetV(key string)string  {
	o.RLock()
	defer o.RUnlock()
	if v,ok:=o.m[key];ok{
		value:=v["value"]
		delete(o.m,key)
		return value
	}
	return ""
}
func ShareInstance() CacheIF {
    once.Do(func() {
    	o=&CacheS{}
    	o.m=make(map[string]map[string]string,1000)
    	go startPool(o)
	})
    return o

}

func startPool(o *CacheS)  {
	for{
		time.Sleep(time.Second*3)
		o.RLock()
		for k,v:=range o.m{

			if timestamp,ok:=v["time"];ok{
				i, _ := strconv.Atoi(timestamp)
				if time.Now().Unix()-int64(i)>10 {
					delete(o.m,k)
				}
			}
		}
		fmt.Println("cache的值",o.m)
		o.RUnlock()

	}
}